#include "BoxlineManager.h"

#include "systemconfiguration.h"
#include "component_log.h"
#include "componentmanager.h"

BoxlineManager::BoxlineManager(QObject* parent)
	: ComponentBase(parent)
{
	m_name = u8"输送位置管理组件";
	m_type = Component::component_boxline;
}

BoxlineManager::~BoxlineManager()
{}

Boxline* BoxlineManager::GetBoxlineByID(const QString& id)
{
	if (m_lineList.contains(id)) {
		return m_lineList.value(id);
	}
	log_error("Not find id ={}", id);
	return nullptr;
}

void* BoxlineManager::GetPoint(const QString& id)
{
	return GetBoxlineByID(id);
}

// 组件初始化处理函数
int BoxlineManager::ComponentInit()
{
	auto ids = syscfg->GetBoxlineIds();
	for (auto id : ids) {
		auto temp = new Boxline(id);
		if (temp->Init()) {
			m_lineList.insert(id, temp);
			log_trace("line {} load success", id);
		} else {
			log_error("line {} load failed", id);
		}
	}

	if (m_lineList.size() <= 0) {
		log_trace("line num is 0, dont need Boxline component");
		return -1;
	}

	// 订阅wcsmsg组件的任务消息
	auto wcs = m_ob->GetComponent(Component::component_wcsrec);
	if (wcs == nullptr) {
		SetErrmsg("获取wcs消息组件未加载", false);
		return -99;
	}
	bool ret = wcs->RegisterSubscriberFunction((int)WCSMsgType::wcs_msg_plate_arrive, [&](const QByteArray& info) {
		return this->OnSkuArrive(info);
		});
	if (!ret) {
		SetErrmsg("订阅wcs到位消息失败", false);
		return -99;
	}
	ret = wcs->RegisterSubscriberFunction((int)WCSMsgType::wcs_msg_boxline, [&](const QByteArray& info) {
		return this->OnBoxlineState(info);
		});
	if (!ret) {
		SetErrmsg("订阅wcs到位消息失败", false);
		return -99;
	}

	return 0;
}
/*自检接口*/
bool BoxlineManager::ComponentCheckSelfState()
{
	return true;
}

/*复位接口*/
bool BoxlineManager::ComponentSelfReset()
{
	return true;
}

int BoxlineManager::OnSkuArrive(const QByteArray& data)
{
	SkuArrive info = {};
	info.fromJson(data);
	if (info.type() != 1) {	// 只处理物料到位的信息
		return -1;
	}

	if (m_lineList.contains(info.boxLine())) {
		if (m_lineList[info.boxLine()]->SetSkuArrived(info.num(), info.skuNo())) {
			return 0;
		}
	}
	log_error("Update sku arrive info for {} failed", info.boxLine());
	return -1;
}
int BoxlineManager::OnBoxlineState(const QByteArray& data)
{
	BoxlineState info = {};
	info.fromJson(data);
	if (m_lineList.contains(info.boxLine())) {
		if (m_lineList[info.boxLine()]->ChangeBoxlineState(info.state())) {
			return 0;
		}
	}
	log_error("Update sku State info for {} failed", info.boxLine());
	return -1;
}
